package offer;

public class Offer13 {

    public boolean exist(char[][] board, String word) {
        char[] words = word.toCharArray();
        boolean res = false;
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                res=dfs(board,words,i,j,0);

                //todo：我能从一个位置出发找到满足条件的结果
                if (res==true){
                    return  true;
                }
            }
        }
        return  res;
    }

    public boolean  dfs(char[][] board,char[]  words,int i,int j,int k){
        if (i<0||i> board.length-1||j<0||j> board[0].length-1||board[i][j]!=words[k]||k> words.length-1){
            return false;
        }
        if (k== words.length-1){
            return  true;
        }
        boolean res;
        board[i][j]='\0';
        res=dfs(board,words,i-1,j,k+1)||dfs(board,words,i+1,j,k+1)
                ||dfs(board,words,i,j-1,k+1)||dfs(board,words,i,j+1,k+1);
        board[i][j]=words[k];
        return  res;
    }



    int sum(int x){
        int sum=0;
        while (x>0){
            sum+=x%10;
            x=x/10;
        }
        return  sum;
    }

     int m,n,k;
    boolean[][]  record;
    public int movingCount(int m, int n, int k) {
        this.m=m;
        this.n=n;
        this.k=k;
        record=new boolean[m][n];
        return  find(0,0,k);
    }


    int find(int x,int y,int k){
        if (x>=m||x<0||y>=n||y<0||sum(x)+sum(y)>k||record[x][y]){
            return  0;
        }
        record[x][y]=true;
//        todo: 从0，0出发 这样子以后就只用向右 向下 进行遍历
        return  1+find(x+1,y,k)+find(x,y+1,k);
    }



}
